package com.market.util;

import java.util.LinkedList;
import java.util.List;

import com.market.domain.BaseObject;

public class CollectionUtil<BO extends BaseObject> {
	/**
	 * Mark all target element contain in source to be selected
	 * 
	 * @param source
	 *            collection going to be marked
	 * @param target
	 */
	public List<BO> markList(List<BO> source, List<BO> target) {

		for (BaseObject o : source) {
			o.setSelected(false);
		}

		for (BaseObject o : source) {
			for (BaseObject t : target) {
				if (o.equalsId(t)) {
					o.setSelected(true);
					break;
				}
			}
		}

		return source;
	}

	/**
	 * This method extract all those selected elements from a List source
	 * 
	 * @param source
	 * @return
	 */

	public List<BO> extractSelected(List<BO> source) {
		List<BO> selectedObjects = new LinkedList<BO>();
		for (BO o : source) {
			if (o.getSelected() == true) {
				selectedObjects.add(o);
			}
		}
		return selectedObjects;
	}

	/**
	 * This method extract all those unselected elements from a List source
	 * 
	 * @param source
	 * @return
	 */

	public List<BO> extractUnSelected(List<BO> source) {
		List<BO> selectedObjects = new LinkedList<BO>();
		for (BO o : source) {
			if (o.getSelected() == false) {
				selectedObjects.add(o);
			}
		}
		return selectedObjects;
	}

	/**
	 * Use bo's Id to find an equal object in list, if can not find, the bo will
	 * be added to list, or add operation will be ignored;
	 * 
	 * @param object
	 */
	public List<BO> add(List<BO> list, BO bo) {
		boolean exist = false;
		for (BO o : list) {
			if (o.equalsId(bo)) {
				exist = true;
				break;
			}
		}
		if (exist == false) {
			list.add(bo);
		}
		return list;
	}
	

	/**
	 * Those objects in bos are not exist in list will be added to list, or add
	 * operation will be ignored, Use object's id to find identical object;
	 * 
	 * @param objects
	 */
	public List<BO> addAll(List<BO> list, List<BO> bos) {
		for (BO bo : bos) {
			list = this.add(list, bo);
		}
		return list;
	}
	
	
	/**
	 * Use bo's id to find an equal object in list, if find that object will be remove from list
	 * @param list
	 * @param bo
	 * @return
	 */
	public List<BO> remove(List<BO> list, BO bo){
		for(int i = 0; i < list.size(); i++){
			if(list.get(i).equalsId(bo)){
				list.remove(i);
				return list;
			}
		}
		return list;
	}
	
	
	
	
	
	/**
	 * Those objects that exist in list and bos will be removed from list, otherwise, the remove
	 * operation will be ignored. 
	 * @param list
	 * @param bos
	 * @return
	 */
	public List<BO> removeAll(List<BO> list, List<BO> bos){
		for(BO bo : bos){
			list = this.remove(list, bo);
		}
		return list;
	}

	public void clearSelection(List<BO> list) {
		for (BO bo : list) {
			bo.setSelected(Boolean.FALSE);
		}
	}

}
